package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.UserPojo;
import com.lei.springbootpractice.pojo.ConsolePojo;
import com.lei.springbootpractice.pojo.ConversationPojo;
import com.lei.springbootpractice.pojo.NotificationStatusPojo;
import com.lei.springbootpractice.service.UserService;
import com.lei.springbootpractice.service.OrdersService;
import com.lei.springbootpractice.service.ConsoleService;
import com.lei.springbootpractice.service.ConversationService;
import com.lei.springbootpractice.service.NotificationService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/customer-service")
public class CustomerServiceController {

    private final UserService userService;
    private final OrdersService ordersService;
    private final ConsoleService consoleService;
    private final ConversationService conversationService;
    private final NotificationService notificationService;

    @Autowired
    public CustomerServiceController(UserService userService, OrdersService ordersService, 
                                   ConsoleService consoleService, ConversationService conversationService,
                                   NotificationService notificationService) {
        this.userService = userService;
        this.ordersService = ordersService;
        this.consoleService = consoleService;
        this.conversationService = conversationService;
        this.notificationService = notificationService;
    }

    @GetMapping("/dashboard")
    public String dashboard(HttpSession session, Model model) {
        String userID = (String) session.getAttribute("loggedInUser");
        if (userID == null) {
            return "redirect:/login";
        }
        
        UserPojo user = userService.getUserByUserID(userID);
        if (user == null || !"customer_service".equals(user.getRole())) {
            return "redirect:/login?error=access_denied";
        }
        
        // 获取对话统计
        try {
            List<ConversationPojo> customerList = consoleService.getCustomerListForCustomerService(userID);
            int totalConversations = customerList.size();
            
            // 添加调试信息
            System.out.println("=== 客服工作台调试信息 ===");
            System.out.println("客服ID: " + userID);
            System.out.println("客服姓名: " + user.getUserName());
            System.out.println("对话列表大小: " + totalConversations);
            if (customerList != null && !customerList.isEmpty()) {
                for (ConversationPojo conv : customerList) {
                    System.out.println("对话ID: " + conv.getConversationId() + 
                                     ", 顾客: " + conv.getCustomerName() + 
                                     ", 最后消息: " + conv.getLastMessage() + 
                                     ", 消息数: " + conv.getMessageCount());
                }
            } else {
                System.out.println("对话列表为空或null");
            }
            System.out.println("=== 调试信息结束 ===");
            
            model.addAttribute("username", user.getUserName());
            model.addAttribute("userRole", user.getRole());
            model.addAttribute("totalConversations", totalConversations);
            model.addAttribute("customerList", customerList);
        } catch (Exception e) {
            System.out.println("=== 获取对话列表异常 ===");
            System.out.println("异常信息: " + e.getMessage());
            e.printStackTrace();
            System.out.println("=== 异常信息结束 ===");
            
            model.addAttribute("username", user.getUserName());
            model.addAttribute("userRole", user.getRole());
            model.addAttribute("totalConversations", 0);
            model.addAttribute("customerList", java.util.Collections.emptyList());
        }
        
        return "customer-service/dashboard";
    }
    
    @GetMapping("/conversations")
    public String conversations(HttpSession session, Model model) {
        String userID = (String) session.getAttribute("loggedInUser");
        if (userID == null) {
            return "redirect:/login";
        }
        
        UserPojo user = userService.getUserByUserID(userID);
        if (user == null || !"customer_service".equals(user.getRole())) {
            return "redirect:/login?error=access_denied";
        }
        
        try {
            List<ConversationPojo> customerList = consoleService.getCustomerListForCustomerService(userID);
            model.addAttribute("username", user.getUserName());
            model.addAttribute("userRole", user.getRole());
            model.addAttribute("customerList", customerList);
        } catch (Exception e) {
            model.addAttribute("username", user.getUserName());
            model.addAttribute("userRole", user.getRole());
            model.addAttribute("customerList", java.util.Collections.emptyList());
            model.addAttribute("error", "获取对话列表失败：" + e.getMessage());
        }
        
        return "customer-service/conversations";
    }
    
    @GetMapping("/chat/{conversationId}")
    public String chat(@PathVariable String conversationId, HttpSession session, Model model) {
        String userID = (String) session.getAttribute("loggedInUser");
        if (userID == null) {
            return "redirect:/login";
        }
        
        UserPojo user = userService.getUserByUserID(userID);
        if (user == null || !"customer_service".equals(user.getRole())) {
            return "redirect:/login?error=access_denied";
        }
        
        try {
            // 验证对话是否属于该客服
            ConversationPojo conversation = conversationService.getConversationById(conversationId);
            if (conversation == null || !conversation.getCustomerServiceId().equals(userID)) {
                return "redirect:/customer-service/conversations?error=conversation_not_found";
            }
            
            UserPojo customer = userService.getUserByUserID(conversation.getCustomerId());
            if (customer == null) {
                return "redirect:/customer-service/conversations?error=customer_not_found";
            }
            
            List<ConsolePojo> messages = consoleService.getConversationMessages(conversationId);
            model.addAttribute("username", user.getUserName());
            model.addAttribute("userRole", user.getRole());
            model.addAttribute("customer", customer);
            model.addAttribute("messages", messages);
            model.addAttribute("conversationId", conversationId);
            model.addAttribute("conversation", conversation);
        } catch (Exception e) {
            model.addAttribute("username", user.getUserName());
            model.addAttribute("userRole", user.getRole());
            model.addAttribute("messages", java.util.Collections.emptyList());
            model.addAttribute("conversationId", conversationId);
            model.addAttribute("error", "获取对话记录失败：" + e.getMessage());
        }
        
        return "customer-service/chat";
    }
    
    @PostMapping("/send-message")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody Map<String, String> request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            String conversationId = request.get("conversationId");
            String message = request.get("message");
            
            if (conversationId == null || conversationId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "对话ID不能为空");
                return ResponseEntity.ok(response);
            }
            
            if (message == null || message.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "消息内容不能为空");
                return ResponseEntity.ok(response);
            }
            
            boolean success = consoleService.sendMessageFromCustomerService(userID, conversationId, message.trim());
            
            if (success) {
                response.put("success", true);
                response.put("message", "消息发送成功");
                
                // 返回最新的消息列表
                List<ConsolePojo> messages = consoleService.getConversationMessages(conversationId);
                List<Map<String, Object>> messageList = new ArrayList<>();
                for (ConsolePojo msg : messages) {
                    Map<String, Object> msgData = new HashMap<>();
                    UserPojo sender = userService.getUserByUserID(msg.getSenderId());
                    
                    msgData.put("content", msg.getContent());
                    msgData.put("createTime", msg.getCreateTime());
                    msgData.put("senderName", sender.getUserName());
                    msgData.put("isFromCustomer", !userID.equals(msg.getSenderId()));
                    
                    messageList.add(msgData);
                }
                response.put("messages", messageList);
            } else {
                response.put("success", false);
                response.put("message", "消息发送失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "发送失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/get-messages/{conversationId}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getMessages(@PathVariable String conversationId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 验证对话是否属于该客服
            ConversationPojo conversation = conversationService.getConversationById(conversationId);
            if (conversation == null || !conversation.getCustomerServiceId().equals(userID)) {
                response.put("success", false);
                response.put("message", "对话不存在或无权限访问");
                return ResponseEntity.ok(response);
            }
            
            // 获取对话记录
            List<ConsolePojo> messages = consoleService.getConversationMessages(conversationId);
            
            // 为每条消息添加发送者信息
            List<Map<String, Object>> messageList = new ArrayList<>();
            for (ConsolePojo message : messages) {
                Map<String, Object> msgData = new HashMap<>();
                UserPojo sender = userService.getUserByUserID(message.getSenderId());
                
                msgData.put("content", message.getContent());
                msgData.put("createTime", message.getCreateTime());
                msgData.put("senderName", sender.getUserName());
                msgData.put("isFromCustomer", !userID.equals(message.getSenderId()));
                
                messageList.add(msgData);
            }
            
            response.put("success", true);
            response.put("messages", messageList);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取消息失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/api/conversations-count")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getConversationsCount(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 获取该客服的对话数量
            List<ConversationPojo> customerList = consoleService.getCustomerListForCustomerService(userID);
            
            response.put("success", true);
            response.put("count", customerList.size());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取对话数量失败：" + e.getMessage());
            response.put("count", 0);
        }
        
        return ResponseEntity.ok(response);
    }
    

    
    @PostMapping("/mark-messages-read")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> markMessagesRead(@RequestBody Map<String, String> request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            String conversationId = request.get("conversationId");
            if (conversationId == null || conversationId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "对话ID不能为空");
                return ResponseEntity.ok(response);
            }
            
            // 验证对话是否属于该客服
            ConversationPojo conversation = conversationService.getConversationById(conversationId);
            if (conversation == null || !conversation.getCustomerServiceId().equals(userID)) {
                response.put("success", false);
                response.put("message", "对话不存在或无权限访问");
                return ResponseEntity.ok(response);
            }
            
            // 清零客服未读消息计数
            conversationService.clearUnreadCount(conversationId, false);
            response.put("success", true);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "标记已读失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/unread-count")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getUnreadCount(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 使用新的通知系统获取未读消息数
            int unreadCount = notificationService.getMessageUnreadCount(userID);
            response.put("success", true);
            response.put("unreadCount", unreadCount);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取未读消息数失败：" + e.getMessage());
            response.put("unreadCount", 0);
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/api/conversations-list")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getConversationsList(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 获取该客服的对话列表
            List<ConversationPojo> customerList = consoleService.getCustomerListForCustomerService(userID);
            
            response.put("success", true);
            response.put("conversations", customerList);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取对话列表失败：" + e.getMessage());
            response.put("conversations", java.util.Collections.emptyList());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/api/conversation-status/{conversationId}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getConversationStatus(@PathVariable String conversationId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 检查对话是否存在且属于该客服
            ConversationPojo conversation = conversationService.getConversationById(conversationId);
            if (conversation == null) {
                response.put("success", true);
                response.put("exists", false);
                response.put("message", "对话不存在");
            } else if (!conversation.getCustomerServiceId().equals(userID)) {
                response.put("success", true);
                response.put("exists", false);
                response.put("message", "无权限访问此对话");
            } else {
                response.put("success", true);
                response.put("exists", true);
                response.put("status", conversation.getStatus());
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查对话状态失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/notifications")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getNotifications(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userID = (String) session.getAttribute("loggedInUser");
            if (userID == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userID);
            if (user == null || !"customer_service".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 获取最新的通知列表
            List<NotificationStatusPojo> notifications = notificationService.getUnreadNotifications(userID, 10);
            response.put("success", true);
            response.put("notifications", notifications);
            response.put("unreadCount", notifications.size());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取通知失败：" + e.getMessage());
            response.put("notifications", new ArrayList<>());
        }
        
        return ResponseEntity.ok(response);
    }
}
